﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.Entity;
using Jinjia.Approve.Entity.Entity.JJFlow;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.Model.Input.JJFlow;
using Jinjia.Approve.Model.VM;
using Jinjia.Core.BaseInfrastructure.StorageModel.Model;
using Jinjia.Core.UnitOfWork.UnitOfWorkComponent;
using SqlSugar;

namespace Jinjia.Approve.Repository.JJFlow
{
    public class FlowMappingRepository : IFlowMappingRepository
    {
        private readonly ISqlSugarClient _db;

        public FlowMappingRepository(IUnitOfWork unitOfWork)
        {
            _db = unitOfWork.GetDbClient();
        }

        public async Task<jj_flow_mapping_tbl> GetByModularKey(string modular_key)
        {
            var jjFlowMappingTbl = await _db.Queryable<jj_flow_mapping_tbl>().Where(x => x.modular_key == modular_key && x.deleted == 0).FirstAsync();
            return jjFlowMappingTbl;
        }

        public async Task<Dictionary<int, string>> GetByTemplateID(int templateID)
        {
            return (await _db.Queryable<jj_flow_mapping_tbl>()
                    .Where(t => t.template_id == templateID)
                    .ToListAsync())
                .ToDictionary(t => t.id, t => t.modular_name);
        }

        public async Task<List<jj_flow_mapping_tbl>> GetMappingByIds(List<int> ids)
        {
            return await _db.Queryable<jj_flow_mapping_tbl>()
                .Where(t => ids.Contains(t.id))
                .Where(t => t.deleted == 0)
                .ToListAsync();
        }

        public async Task UpdateMappingTemplateId(int templateId, List<int> id, int userId)
        {
            await _db.Updateable<jj_flow_mapping_tbl>()
                .SetColumns(x => new jj_flow_mapping_tbl()
                {
                    template_id = templateId,
                    update_user_id = userId,
                    update_time = DateTime.Now
                })
                .Where(x => id.Contains(x.id))
                .ExecuteCommandAsync();
        }

        public async Task ClearTemplateIDByTemplateID(int templateID, int userId)
        {
            await _db.Updateable<jj_flow_mapping_tbl>()
                .SetColumns(x => new jj_flow_mapping_tbl()
                {
                    template_id = 0,
                    update_user_id = userId,
                    update_time = DateTime.Now
                })
                .Where(x => x.template_id == templateID)
                .ExecuteCommandAsync();
        }

        public async Task<PageListSearchResultVM<JJMappingViewModel>> GetMappingPageList(JJMappingSearchCondition searchCondition, int user_id)
        {
            var queryable = _db.Queryable<jj_flow_mapping_tbl, jj_flow_template, erpa_user_tbl, erpa_user_tbl>((a, b, d, e) =>
                new JoinQueryInfos(
                    JoinType.Left, a.template_id == b.id,
                    JoinType.Left, a.create_user_id == d.id,
                    JoinType.Left, a.update_user_id == e.id
                ));
            queryable.Where(a => a.deleted == 0);

            if (!string.IsNullOrWhiteSpace(searchCondition.todo_list_type))
            { 
                queryable.Where(a => a.todo_list_type.Contains(searchCondition.todo_list_type) );
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.modular_key))
            {
                queryable.Where(a => a.modular_key.Contains(searchCondition.modular_key));
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.modular_name))
            {
                queryable.Where(a => a.modular_name.Contains(searchCondition.modular_name));
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.remark))
            {
                queryable.Where(a => a.remark.Contains(searchCondition.remark));
            }

            var orderby = " a.create_time desc"; //"a.activity_state desc,a.deleted asc,a.activity_end_time desc,a.create_time desc  ";
            queryable.OrderBy(!string.IsNullOrWhiteSpace(searchCondition.order_by) ? searchCondition.order_by + " " + searchCondition.direction : orderby);


            var newQuery = queryable.Select<JJMappingViewModel>(
                @" a.id,a.modular_key,a.modular_name,a.template_id,a.create_user_id,a.create_time,a.update_user_id,a.update_time,a.remark, a.todo_list_type,
             b.template_name,
             d.user_name as create_user_name,e.user_name as update_user_name ");

            var result = await newQuery.ToPageListAsync(searchCondition, new DynamicTableHeaderInput()
            {
                MethodName = "ERPAssistant.Api.Controllers.JJFlowController.GetMappingPageList",
                UserId = user_id
            });

            return result;
        }

        public async Task<int> GetMappingCount(string modular_key, int id)
        {
            var mappingCount = await _db.Queryable<jj_flow_mapping_tbl>().
                Where(t => t.modular_key == modular_key).
                Where(t => t.id != id).
                Where(t => t.deleted == 0).
                CountAsync();
            return mappingCount;
        }

        public async Task<jj_flow_mapping_tbl> GetMappingId(int id)
        {
            return await _db.Queryable<jj_flow_mapping_tbl>().Where(t => t.id==id).FirstAsync();
        }

        public async Task<int> Save(jj_flow_mapping_tbl data)
        {
            if (data.id <= 0) //新增
            {
                var id = await _db.Insertable(data).ExecuteReturnIdentityAsync();
                return id;
            }
            else
            {
                await _db.Updateable(data)
                    .Where(x => x.id == data.id)
                    .ExecuteCommandAsync();
                return data.id;
            }
        }
    }
}